﻿using Entity.PointsActivety;
using Mapster;

namespace Services.PointsActivity;

/// <summary>
/// 排队免单商户端接口
/// </summary>
[Authorize]
[ApiDescriptionSettings("排队免单")]
public class StorePointsActivity : BaseServices
{
    private readonly ISqlSugarClient db;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="db"></param>
    public StorePointsActivity(ISqlSugarClient db)
    {
        this.db = db;
    }

    /// <summary>
    /// 编辑添加活动
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public async Task<object> Edit(Dto.EditPointsActiveDto e)
    {
        var data = e.Adapt<Entity.PointsActivety.PointsActivity>();

        data.StoreId = STOREID;

        bool state = false;

        if (data.Id == 0)
        {
            state = await db.Insertable(data).ExecuteReturnIdentityAsync() > 0;
        }
        else
        {
            //更新时不能更新 奖池金额,奖池累计金额,和当前排队序号
            state = await db.Updateable(data).IgnoreColumns("totalPrice,currentPrice,index").ExecuteCommandHasChangeAsync();
        }

        return Msg(state);
    }

    /// <summary>
    /// 获取参与排队用户
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<object> GetActiveUser(int id)
    {
        var data = await db.Queryable<Entity.PointsActivety.PointsActivityQueue>()

            .Where(x => x.ActiveId == id && x.StoreId == STOREID)

            .Includes(x => x.Client)

            .ToPagedListAsync(PageNo, PageSize);

        return Ok(data);
    }

    /// <summary>
    /// 获取领取用户记录
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<object> GetResolveUser(int id)
    {
        var data = await db.Queryable<Entity.PointsActivety.PointsActivityQueue>()

            .Where(x => x.ActiveId == id && x.StoreId == STOREID)

            .Where(x => x.State == Entity.PointsActivety.ActiveState.已领奖)

            .OrderBy(x => x.Index, OrderByType.Desc)

            .Includes(x => x.Client)

            .ToPagedListAsync(PageNo, PageSize);

        return Ok(data);
    }

    /// <summary>
    /// 获取踢出用户
    /// </summary>
    /// <returns></returns>
    public async Task<object> GetOutUser(int id)
    {
        var data = await db.Queryable<Entity.PointsActivety.PointsActivityQueue>()

          .Where(x => x.ActiveId == id && x.StoreId == STOREID && x.State == Entity.PointsActivety.ActiveState.已退出)

          .Includes(x => x.Client)

          .ToPagedListAsync(PageNo, PageSize);

        return Ok(data);
    }

    /// <summary>
    /// 获取列表
    /// </summary>
    /// <returns></returns>
    public async Task<object> GetList()
    {
        var data = await db.Queryable<Entity.PointsActivety.PointsActivity>()

            .Where(x => x.StoreId == STOREID)

            .ToPagedListAsync(PageNo, PageSize);

        return Ok(data);
    }

    /// <summary>
    /// 获取详情
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<object> GetDetail(int id)
    {
        var data = await db.Queryable<Entity.PointsActivety.PointsActivity>()

            .FirstAsync(x => x.Id == id);

        return Ok(data);
    }

    /// <summary>
    /// 获取核销信息
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<object> GetResolveInfo(int id)
    {
        //队列信息
        var data = await db.Queryable<PointsActivityQueue>()
            
            .Includes(x=>x.Client)

            .FirstAsync(x => x.Id == id);

        return Ok(data);
    }

    /// <summary>
    /// 确认领奖
    /// </summary>
    /// <returns></returns>
    public async Task<object> Resolve(int id)
    {
        //队列信息
        var data = await db.Queryable<PointsActivityQueue>().FirstAsync(x => x.Id == id);

        if (data == null) return No("没有找到该用户信息");

        if (data.StoreId != STOREID) return No("您无核销权限");
       
        //活动信息
        var active = await db.Queryable<Entity.PointsActivety.PointsActivity>().FirstAsync(x => x.Id == data.ActiveId);

        if (data.State != ActiveState.可领奖) return No("未达到领奖条件");

        bool state = false;

        #region 1.更新队列信息

        data.ResolveTime = DateTime.Now;

        data.State = ActiveState.已领奖;

        state = await db.Updateable(data).ExecuteCommandHasChangeAsync();

        #endregion

        #region 2.更新奖池信息

        active.Index += 1;

        active.CurrentPrice -= data.RealPrice;

        state = await db.Updateable(active).ExecuteCommandHasChangeAsync();

        #endregion

        #region 3.更新下一个领奖用户

        await NextResolveUser(active);

        #endregion

        return Msg(state);
    }

    /// <summary>
    /// 更新下一个领奖者信息
    /// </summary>
    /// <param name="active"></param>
    /// <returns></returns>
    private async Task NextResolveUser(Entity.PointsActivety.PointsActivity active)
    {
        //获取下一个领奖者
        var user = await db.Queryable<Entity.PointsActivety.PointsActivityQueue>().Where(x => x.ActiveId == active.Id && x.Index == active.Index).FirstAsync();

        //没有领奖者 直接返回
        if (user == null) return;

        //奖池金额 大于 用户可以领奖金额 并且
        if (active.CurrentPrice > user.RealPrice && user.State == ActiveState.进行中)
        {
            user.State = Entity.PointsActivety.ActiveState.可领奖;

            await db.Updateable(user).ExecuteCommandHasChangeAsync();
        }
    }

}

